package com.kkm.service.Imp;

import com.kkm.dao.Imp.UserDaoImp;
import com.kkm.dao.UserDao;
import com.kkm.pojo.Consumer;
import com.kkm.pojo.PageBean;
import com.kkm.service.UserService;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 管理用户service接口实现类
 */
public class UserServiceImp implements UserService {
    private UserDao userDao=new UserDaoImp();
    @Override
    public PageBean<Consumer> showUser(String currentPage, int rows) {
        int currPage=Integer.parseInt(currentPage);
        if(currPage<=0){
            currPage=1;
        }
        PageBean<Consumer> pageBean=new PageBean(); //实例化pagebean对象
        int count=userDao.checkUserCount();        //查询记录数

        int totalPage=count%rows==0?count/rows :count/rows+1;
        if(currPage>=totalPage){
            currPage=totalPage;
            System.out.println(currPage+"UserService");
        }

        int index=(currPage-1)*rows;
        List<Consumer> consumers =userDao.showUser(index,rows);

        pageBean.setRows(rows);
        pageBean.setCurrentPage(currPage);
        pageBean.setTotalPage(totalPage);
        pageBean.setTotalCount(count);
        pageBean.setList(consumers);

        return pageBean;

    }

    @Override
    public int addUser(String uname) {
        return 0;
    }

    @Override
    public PageBean<Consumer> checkUser(Map<String, String[]> condition, String currentPage, int rows) {
        int userCount=userDao.checkUserCount();
        int num=0;
        Set<String> keySet=condition.keySet();
        for(String key:keySet) {
            String value = condition.get(key)[0];//获取值
            if (!"".equals(value)) {
                num++;
            }
        }

        if(num>2){
            userCount=userDao.checkUserNum(condition);
        }

        //System.out.println(userCount);
       if(userCount>=1){
        int currPage=Integer.parseInt(currentPage);
        PageBean<Consumer> pageBean=new PageBean(); //实例化pagebean对象

        int totalPage=userCount%rows==0?userCount/rows :userCount/rows+1;
        int index=(currPage-1)*rows;
        List<Consumer> consumers =userDao.checkUser(condition,index,rows);

        pageBean.setRows(rows);
        pageBean.setCurrentPage(currPage);
        pageBean.setTotalPage(totalPage);
        pageBean.setTotalCount(userCount);
        pageBean.setList(consumers);
        return pageBean;
       }
       return null;
    }

    @Override
    public void deleteUser(String uid) {
        userDao.deleteUser(Integer.parseInt(uid));
    }

    @Override
    public Consumer userById(String uid) {
       return userDao.userById(Integer.parseInt(uid));
    }

    @Override
    public void modifyUser(String uid, String username, int sex, Date birth,String phone,String email,String address) {
        int id=Integer.parseInt(uid);
        userDao.modifyUser(id,username,sex,birth,phone,email,address);
    }
}
